# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'SKB18121915052': {  # 恒丰支付  alipay-H5 2.5% 60-5000 loki
        # 支付宝扫码 20-5000 loki
        # 微信扫码 定额 3.6% 20,30,50,100,200,300,500 loki
        # 微信H5 定额 3.6% 20,30,50,100,200,300,500 loki
        'API_KEY': 'fb28606f42f526db55a267f75663c404',
        'gateway': 'https://hfpay.honfox.com/api/v3/cashier.php',
        'query_gateway': 'https://hfpay.honfox.com/api/v3/query.php',
    },
    'SKB18122920088': {
        # 恒丰支付
        # 支付宝H5 3.7% 20-5000 zs
        # 支付宝扫码 3.7% 20-5000 zs
        # 微信扫码 定额 3.8% 20,30,50,100,200,300,500 zs
        # 微信H5 定额 3.8% 20,30,50,100,200,300,500 zs
        'API_KEY': 'e0f1776c367124b1dc1b801956e863a5',
        'gateway': 'https://hfpay.honfox.com/api/v3/cashier.php',
        'query_gateway': 'https://hfpay.honfox.com/api/v3/query.php',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = 'merchant={}&qrtype={}&customno={}&money={}&sendtime={}&notifyurl={}&backurl={}&risklevel={}{}'.format(
        d['merchant'], d['qrtype'],
        d['customno'], d['money'],
        d['sendtime'], d['notifyurl'], d['backurl'], d['risklevel'], key)
    _LOGGER.info("hengfengpay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'merchant={}&qrtype={}&customno={}&sendtime={}&orderno={}&money={}&paytime={}&state={}{}'.format(
        d['merchant'], d['qrtype'],
        d['customno'], d['sendtime'],
        d['orderno'], d['money'], d['paytime'], d['state'], key)
    _LOGGER.info("hengfengpay notify sign str: %s", s)
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = 'merchant={}&customno={}&sendtime={}{}'.format(
        d['merchant'], d['customno'], d['sendtime'], key)
    _LOGGER.info("hengfengpay notify sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("hengfengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'aph5'
    elif service == 'alipayscan':
        return 'ap'
    elif service == 'wechatscan':
        return 'wp'
    elif service == 'wechath5':
        return 'wph5'
    return 'aph5'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant', app_id),
        ('qrtype', _get_pay_type(service)),
        ('customno', str(pay.id)),
        ('money', '%.2f' % pay_amount),
        ('sendtime', int(time.time())),
        ('notifyurl', '{}/pay/api/{}/hengfengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('backurl', '{}/pay/api/{}/hengfengpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('risklevel', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("hengfengpay create: %s", json.dumps(parameter_dict))
    _LOGGER.info("hengfengpay order_id is: %s", parameter_dict['customno'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('hengfengpay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("hengfengpay notify body: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['customno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('hengfengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['state'])
    trade_no = data['orderno']
    total_fee = float(data['money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0 未处理 1 交易成功 2 支付失败 3 关闭交易 4 支付超时
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('hengfengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant', app_id),
        ('customno', str(pay_order.id)),
        ('sendtime', int(time.time())),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('hengfengpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('hengfengpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        _LOGGER.info("hengfengpay query response body: %s", data)
        mch_id = pay_order.mch_id
        trade_status = str(data['state'])
        total_fee = float(data['money'])
        trade_no = data['orderno']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('hengfengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
